<script setup lang="ts">
import dayjs from "dayjs";
import leaderSelect from "./leaderSelect.vue";
import { ref, reactive, onMounted, h, toRaw } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { regionData } from "@/utils/chinaArea";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";

import { tags_list } from "@/api/tag"
import { customerLeaderData_performance_c, customerLeaderData_listByType, customerLeaderData_transfer, customerLeaderData_transfer_batch } from "@/api/customer"

import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";

import Eye from "~icons/ri/Eye-line";
import Refresh from "~icons/ep/refresh";
import Checkbox from "~icons/ri/checkbox-fill";
import Arrowleftright from "~icons/ri/arrow-left-right-line";

import CustomerDetail from "@/components/customerDetail/index.vue"

const props = defineProps({
  info: {
    type: Object,
    required: true
  },
})

const formRef = ref();
const statisticTabList = reactive([{
  name: '今日',
  created_at: ''
}, {
  name: '昨日',
  created_at: ''
}, {
  name: '本周',
  created_at: ''
}, {
  name: '上周',
  created_at: ''
}, {
  name: '本月',
  created_at: ''
}, {
  name: '上月',
  created_at: ''
}, {
  name: '总计',
  created_at: ''
}])
const statisticTab = ref(0)
const statisticLoading = ref(false)
const statisticInfo = ref({
  receive_num: 0,
  enter_num: 0,
  follow_num: 0,
  deal_num: 0
});
const labelList = ref([])
const sourceList = ref([{
  value: "exchange",
  label: "兑领"
}, {
  value: "third",
  label: "第三方自导入"
}])
const statusList = ref([{
  value: "noconnect",
  label: "未接通未确定"
}, {
  value: "unkown",
  label: "接通未确定"
}, {
  value: "refuse",
  label: "无意向"
}, {
  value: "intend",
  label: "有意向"
}])
const dealHistoryList = ref([{
  value: 0,
  label: "未成交过"
}, {
  value: 1,
  label: "成交过"
}])
const form = reactive({
  tag_id: "",
  address: "",
  status: "",
  deal_history: "",
  target_staff_id: props.info.id,
  page: 1,
  size: 10
});
const dataList = ref([]);
const loading = ref(true);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const columns: TableColumnList = [
  {
    type: "selection",
    align: "left"
  },
  {
    label: "企业名称",
    prop: "company_name",
    minWidth: 150
  },
  {
    label: "客户名称",
    prop: "name",
    minWidth: 100
  },
  {
    label: "客户标签",
    prop: "tag_ids",
    minWidth: 140,
    formatter: ({ tag_ids }) => {
      if (!tag_ids) return ''
      let tagIds = tag_ids.split(',').map(item => item.replaceAll('_', ''))
      return tagIds.map(item => labelList.value.find(tag => tag.id === item)?.name).join(',')
    }
  },
  {
    label: "地区",
    prop: "address_path",
    minWidth: 140
  },
  {
    label: "被拨次数",
    prop: "called_times",
    minWidth: 100
  },
  {
    label: "客户状态",
    prop: "intend_status",
    minWidth: 100,
    formatter: ({ intend_status }) => {
      if (!intend_status) return ''
      return statusList.value.filter(item => item.value == intend_status)[0].label
    }
  },
  {
    label: "来源",
    prop: "source",
    minWidth: 60,
    formatter: ({ source_by }) => {
      if (!source_by) return ''
      return sourceList.value.filter(item => item.value == source_by)[0].label
    }
  },
  {
    label: "最近跟进时间",
    prop: "called_at",
    minWidth: 120,
    formatter: ({ called_at }) =>  called_at == 0 ? '' : dayjs.unix(called_at).format("YYYY-MM-DD")
  },
  {
    label: "最新成交时间",
    prop: "deal_latestTime",
    minWidth: 120,
    formatter: ({ deal_latestTime }) =>  deal_latestTime == 0 ? '' : dayjs.unix(deal_latestTime).format("YYYY-MM-DD")
  },
  {
    label: "操作",
    fixed: "right",
    slot: "operation"
  }
];

const tableRef = ref();
const multipleSelection = ref([]);
const detailInfo = ref();

const detailRef = ref();
function lookCustomer(row) {
  detailInfo.value = row;
  detailRef.value.openDrawer(row.id);
}

function handleSizeChange(val: number) {
  form.size = val;
  pagination.pageSize = val
  onSearch(); // 刷新表格数据
}

function handleCurrentChange(val: number) {
  form.page = val;
  pagination.currentPage = val
  onSearch(); // 刷新表格数据
}

function handleSelectionChange(val) {
  multipleSelection.value = val;
}

// 转移给他人
const leaderSelectRef = ref()
function personnelSelectClick() {
  addDialog({
    title: "转移给他人",
    props: {
      formInline: {
        leader: null,
        leader_name: "",
      }
    },
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(leaderSelect, { ref: leaderSelectRef, formInline: null } ),
    beforeSure: (done, { options }) => {
      const curData = options.props.formInline
      if (curData.leader) {
        if (multipleSelection.value.length) {
          customerLeaderData_transfer_batch({
            ids: multipleSelection.value.map(item => `${item.id}:${item.table_at}:${item.version}`).join(","),
            to_target_staff_id: curData.leader
          }).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, {
                type: "success"
              });
              setTimeout(() => {
                done(); // 关闭弹框
                multipleSelection.value = []
                onSearch();
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        } else {
          customerLeaderData_transfer({
            id: detailInfo.value.id,
            table_at: detailInfo.value.table_at,
            version: detailInfo.value.version,
            to_target_staff_id: curData.leader
          }).then(res => {
            if (res.code == 1000) {
              message(`操作成功！`, {
                type: "success"
              });
              setTimeout(() => {
                done(); // 关闭弹框
                detailRef.value.closeDrawer();
                onSearch();
              }, 1000);
            } else {
              message(res.msg, { type: "error" });
            }
          });
        }
      } else {
        message(`请选择人员！`, { type: "error" });
      }
    }
  })
}

function handleSelectionClear() {
  const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
  clearSelection();
}

async function onSearch() {
  loading.value = true;

  let queryFrom = { ...form };

  if (queryFrom.address && queryFrom.address.length) queryFrom.address = queryFrom.address.join('/')

  const result = await customerLeaderData_listByType(toRaw(queryFrom));

  dataList.value = result.data.list;
  pagination.total = result.data.total;

  setTimeout(() => {
    loading.value = false;
  }, 500);
}

const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

onMounted(() => {
  onSearch();

  getLabelList()
  getTimeRanges()
  getPerformance()
});

// 获取客户标签
function getLabelList() {
  tags_list({
    page: 1,
    pagesize: 999,
    status: 1
  }).then(res => {
    labelList.value = res.data
  })
}

/**
 * 获取各种时间范围
 * @returns {Object} 包含各种时间范围的对象
 */
function getTimeRanges() {
  const now = new Date();

  // 格式化日期为 YYYY-MM-DD HH:mm:ss
  const formatDate = (date) => {
    const pad = (num) => num.toString().padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
           `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  };

  // 设置时间为当天的开始(00:00:00)或结束(23:59:59)
  const setTime = (date, isStart) => {
    date.setHours(isStart ? 0 : 23);
    date.setMinutes(isStart ? 0 : 59);
    date.setSeconds(isStart ? 0 : 59);
    date.setMilliseconds(0);
    return date;
  };

  // 今日
  const todayStart = setTime(new Date(now), true);
  const todayEnd = setTime(new Date(now), false);

  // 昨日
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  const yesterdayStart = setTime(new Date(yesterday), true);
  const yesterdayEnd = setTime(new Date(yesterday), false);

  // 本周
  const weekStart = new Date(now);
  weekStart.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1));
  const weekEnd = new Date(weekStart);
  weekEnd.setDate(weekStart.getDate() + 6);
  const thisWeekStart = setTime(new Date(weekStart), true);
  const thisWeekEnd = setTime(new Date(weekEnd), false);

  // 上周
  const lastWeekStart = new Date(weekStart);
  lastWeekStart.setDate(weekStart.getDate() - 7);
  const lastWeekEnd = new Date(lastWeekStart);
  lastWeekEnd.setDate(lastWeekStart.getDate() + 6);
  const prevWeekStart = setTime(new Date(lastWeekStart), true);
  const prevWeekEnd = setTime(new Date(lastWeekEnd), false);

  // 本月
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  const thisMonthStart = setTime(new Date(monthStart), true);
  const thisMonthEnd = setTime(new Date(monthEnd), false);

  // 上月
  const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
  const prevMonthStart = setTime(new Date(lastMonthStart), true);
  const prevMonthEnd = setTime(new Date(lastMonthEnd), false);

  statisticTabList[0].created_at = `${formatDate(todayStart)},${formatDate(todayEnd)}`
  statisticTabList[1].created_at = `${formatDate(yesterdayStart)},${formatDate(yesterdayEnd)}`
  statisticTabList[2].created_at = `${formatDate(thisWeekStart)},${formatDate(thisWeekEnd)}`
  statisticTabList[3].created_at = `${formatDate(prevWeekStart)},${formatDate(prevWeekEnd)}`
  statisticTabList[4].created_at = `${formatDate(thisMonthStart)},${formatDate(thisMonthEnd)}`
  statisticTabList[5].created_at = `${formatDate(prevMonthStart)},${formatDate(prevMonthEnd)}`
  statisticTabList[6].created_at = ''
}

function getPerformance() {
  statisticLoading.value = true
  customerLeaderData_performance_c({
    staff_id: props.info.id,
    created_at: statisticTabList[statisticTab.value].created_at
  }).then(res => {
    statisticInfo.value = res.data;

    statisticLoading.value = false
  });
}
</script>

<template>
  <div class="main">
    <div class="cardTab">
      <el-radio-group
        v-model="statisticTab"
        size="large"
        @change="getPerformance"
      >
        <el-radio-button
          v-for="(item, index) in statisticTabList"
          :key="index"
          :label="item.name"
          :value="index"
        />
      </el-radio-group>
    </div>
    <!-- 数据统计 -->
    <div class="statistics" v-loading="statisticLoading">
      <div class="box">
        <p>领取及分配</p>
        <span>{{ statisticInfo.receive_num }}</span>
      </div>
      <div class="box">
        <p>录入</p>
        <span>{{ statisticInfo.enter_num }}</span>
      </div>
      <div class="box">
        <p>跟进</p>
        <span>{{ statisticInfo.follow_num }}</span>
      </div>
      <div class="box">
        <p>成交</p>
        <span>{{ statisticInfo.deal_num }}</span>
      </div>
      <div class="l_t"></div>
      <div class="l_l"></div>
      <div class="r_t"></div>
      <div class="r_l"></div>
    </div>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item prop="tag_id">
        <el-select
          v-model="form.tag_id"
          placeholder="客户标签"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in labelList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="address">
        <el-cascader
          v-model="form.address"
          placeholder="所在地区"
          :options="regionData"
          :props="{ checkStrictly: true, value: 'label' }"
          clearable
          class="w-[120px]!"
        />
      </el-form-item>
      <el-form-item prop="status">
        <el-select
          v-model="form.status"
          placeholder="客户状态"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="deal_history">
        <el-select
          v-model="form.deal_history"
          placeholder="成交状态"
          clearable
          class="w-[120px]!"
        >
          <el-option
            v-for="(item, index) in dealHistoryList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          查询
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="" :columns="columns" @refresh="onSearch">
      <template v-slot="{ size, dynamicColumns }">
        <!-- 多选显示 -->
        <div class="multipleInner" v-if="multipleSelection.length">
          <IconifyIconOffline
            :icon="Checkbox"
            style="color: #fff; width: 18px; height: 18px; cursor: pointer"
            @click="handleSelectionClear"
          />
          <b>已选中 {{ multipleSelection.length }} 项</b>

          <div class="multipHandle" @click="personnelSelectClick">
            <IconifyIconOffline :icon="Arrowleftright" />
            <p>转移给他人</p>
          </div>
        </div>
        <pure-table
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Eye)"
              @click="lookCustomer(row)"
            >
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <CustomerDetail ref="detailRef">
      <template v-slot>
        <el-button
          class="handleButton"
          type="primary"
          :icon="useRenderIcon(Arrowleftright)"
          @click="personnelSelectClick"
        >
          转移给他人
        </el-button>
      </template>
    </CustomerDetail>
  </div>
</template>

<style scoped lang="scss">
.main {
  height: 100%;
  padding-top: 20px;
}

.statistics {
  width: 100%;
  height: 40px;
  background-color: #f3f6f9;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  position: relative;

  .box {
    display: flex;
    align-items: center;
    font-size: 14px;

    p {
      color: #000;
      margin-right: 7px;
    }

    span {
      color: var(--pure-theme-menu-active-before);
      font-weight: bold;
    }
  }

  .l_t {
    position: absolute;
    left: 0;
    top: 0;
    width: 12px;
    height: 12px;
    border-top: 2px solid var(--pure-theme-menu-active-before);
    border-left: 2px solid var(--pure-theme-menu-active-before);
  }

  .l_l {
    position: absolute;
    right: 0;
    top: 0;
    width: 12px;
    height: 12px;
    border-top: 2px solid var(--pure-theme-menu-active-before);
    border-right: 2px solid var(--pure-theme-menu-active-before);
  }

  .r_t {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 12px;
    height: 12px;
    border-bottom: 2px solid var(--pure-theme-menu-active-before);
    border-left: 2px solid var(--pure-theme-menu-active-before);
  }

  .r_l {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 12px;
    height: 12px;
    border-bottom: 2px solid var(--pure-theme-menu-active-before);
    border-right: 2px solid var(--pure-theme-menu-active-before);
  }
}

:deep(.el-form) {
  padding-top: 20px;
  padding-left: 0;
}

.multipleInner {
  background-color: var(--pure-theme-menu-active-before);
  height: 45px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  font-size: 14px;
  color: #ffffff;

  b,
  p {
    margin-left: 3px;
  }

  .multipHandle {
    padding: 5px 8px;
    margin-left: 30px;
    display: flex;
    align-items: center;
    cursor: pointer;
    border-radius: 5px;
    transition: all 0.1s;

    svg {
      color: #ffffff;
    }

    &:hover {
      background-color: #ffffff;
      color: #000000;

      :deep(svg) {
        color: #000000;
      }
    }
  }
}

:deep(.handleButton) {
  margin-top: 30px;
}
</style>
